package com.ggqq.singlemodel;

/*懒汉式单例模式*/  //(不安全，可以通过反射破解)
public class LazyMan {
    private LazyMan(){
        System.out.println(Thread.currentThread().getName()+"ok");
    }
    private volatile static LazyMan lazyMan;

/*    //单线程模式下ok
    public static LazyMan getInstance(){
        if(lazyMan == null){
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }*/

    //多线程模式下加锁  (双重检测模式的  懒汉式单例 DCL懒汉式)
    public static LazyMan getInstance(){
        if(lazyMan==null){
            synchronized (LazyMan.class){
                if(lazyMan == null){
                    lazyMan = new LazyMan();//不是原子性操作，会发生指令重排，需要改进 加volatile关键字
                }
            }
        }
        return lazyMan;
    }
    //多线程并发
    public static void main(String[] args){
        for(int i=0;i<20;i++);{
            new Thread(()->{
                lazyMan.getInstance();
            }).start();

        }
    }
}
